<template>
  <div class="profile-page">
    <el-card class="user-card">
      <div class="user-header">
        <el-avatar :size="72" :src="user?.avatarUrl" class="avatar"></el-avatar>
        <div class="meta">
          <div class="name">
            {{ user?.nickname || user?.username }}
            <el-tag type="success" size="mini" v-if="user?.postCount !== undefined">发布 {{ user.postCount }}</el-tag>
            <el-tag type="danger" size="mini" v-if="user?.likedCount !== undefined" class="ml8">获赞 {{ user.likedCount }}</el-tag>
          </div>
          <div class="bio">{{ user?.bio || '这个人很低调，什么也没写～' }}</div>
          <div class="actions">
            <el-button icon="el-icon-edit" size="small" @click="openEdit">编辑资料</el-button>
            <el-button
              v-if="activeTab==='posts'"
              type="danger"
              size="small"
              class="ml8"
              :plain="!deleteMode"
              icon="el-icon-delete"
              @click="toggleDeleteMode"
            >{{ deleteMode ? '退出删除' : '删除' }}</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="content-card">
      <el-tabs v-model="activeTab" @tab-click="onTab">
        <el-tab-pane label="我发布的分享" name="posts">
          <post-grid
            :list="postList"
            :thumb="thumb"
            :total="postTotal"
            :page.sync="postPage"
            :size="pageSize"
            :selectable="deleteMode"
            :selected-ids="selectedIds"
            @toggle-select="onToggleSelect"
            @load="loadPosts"
          />
          <div v-if="deleteMode" class="delete-bar">
            <div>已选 {{ selectedIds.length }} 项</div>
            <div>
              <el-button size="small" @click="clearSelection">取消选择</el-button>
              <el-button size="small" type="danger" :disabled="selectedIds.length===0" @click="confirmBatchDelete">确认删除</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我点赞的分享" name="likes">
          <post-grid
            :list="likeList"
            :thumb="thumb"
            :total="likeTotal"
            :page.sync="likePage"
            :size="pageSize"
            @load="loadLikes"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog title="编辑个人资料" :visible.sync="editVisible" width="520px" :close-on-click-modal="false">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="88px">
        <el-form-item label="头像">
          <div class="avatar-row">
            <el-avatar :size="64" :src="editForm.avatarUrl"></el-avatar>
            <el-upload
              class="ml12"
              action="/api/oss/image"
              :show-file-list="false"
              :on-success="onAvatarUploaded">
              <el-button size="small">上传头像</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" maxlength="20" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input type="textarea" :rows="3" v-model="editForm.bio" maxlength="80" show-word-limit />
        </el-form-item>
        <el-divider content-position="left">修改密码（可选）</el-divider>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="editForm.oldPassword" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="editForm.newPassword" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认新密" prop="confirmPassword">
          <el-input v-model="editForm.confirmPassword" type="password" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

const PostGrid = {
  name: 'post-grid',
  props: { list: Array, thumb: Object, total: Number, page: Number, size: Number, selectable: Boolean, selectedIds: Array },
  methods: {
    toDetail (id) { this.$router.push('/post/' + id) },
    onPage (p) { this.$emit('update:page', p); this.$emit('load') },
    toggle (id) { this.$emit('toggle-select', id) }
  },
  render (h) {
    return (
      <div>
        <el-row gutter={16}>
          { (this.list || []).map(item =>
            <el-col span={6} key={item.id} style="margin-bottom:16px">
              <el-card nativeOnClick={() => !this.selectable && this.toDetail(item.id)} shadow="hover" body-style={{ padding: '8px', cursor: this.selectable ? 'default' : 'pointer', position: 'relative' }}>
                { this.selectable
                  ? (
                  <el-checkbox
                    value={(this.selectedIds || []).includes(item.id)}
                    onChange={() => this.toggle(item.id)}
                    style="position:absolute;left:8px;top:8px;z-index:2;background:rgba(255,255,255,.85);padding:2px 6px;border-radius:4px"
                  ></el-checkbox>
                    )
                  : null }
                { this.thumb[item.id] ? <img src={this.thumb[item.id]} style="width:100%;height:180px;object-fit:cover;border-radius:6px" /> : null }
                <div style="padding:8px">
                  <div class="pg-title">{item.title}</div>
                  <div class="pg-meta">❤ {item.likeCount || 0} · 评论 {item.commentCount || 0}</div>
                </div>
              </el-card>
            </el-col>
          )}
        </el-row>
        <div style="text-align:center;margin:16px">
          <el-pagination
            current-page={this.page}
            page-size={this.size}
            total={this.total}
            layout="prev, pager, next"
            on-current-change={this.onPage}
          />
        </div>
      </div>
    )
  }
}

export default {
  name: 'Profile',
  components: { PostGrid },
  data () {
    const phoneRule = (r, v, cb) => !v || /^1\d{10}$/.test(v) ? cb() : cb(new Error('手机号格式不正确'))
    const confirmRule = (r, v, cb) => {
      if (!this.editForm.newPassword && !this.editForm.oldPassword && !v) return cb()
      if (v !== this.editForm.newPassword) return cb(new Error('两次密码不一致'))
      cb()
    }
    return {
      user: null,
      activeTab: 'posts',
      postList: [],
      likeList: [],
      postTotal: 0,
      likeTotal: 0,
      postPage: 1,
      likePage: 1,
      pageSize: 12,
      thumb: {},
      editVisible: false,
      deleteMode: false,
      selectedIds: [],
      editForm: { avatarUrl: '', username: '', nickname: '', phone: '', bio: '', oldPassword: '', newPassword: '', confirmPassword: '' },
      editRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 2, max: 20, message: '2-20 个字符', trigger: 'blur' }],
        phone: [{ validator: phoneRule, trigger: 'blur' }],
        oldPassword: [{ validator: (r, v, cb) => { if (!this.editForm.newPassword && !v) return cb(); if (!v) return cb(new Error('请输入原密码')); cb() }, trigger: 'blur' }],
        newPassword: [{ validator: (r, v, cb) => { if (!this.editForm.oldPassword && !v) return cb(); if (!v) return cb(new Error('请输入新密码')); if (v.length < 6) return cb(new Error('至少 6 位')); cb() }, trigger: 'blur' }],
        confirmPassword: [{ validator: confirmRule, trigger: 'blur' }]
      }
    }
  },
  async created () {
    await this.loadMe()
    this.loadPosts()
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
  },
  beforeDestroy () {
    // 移除事件监听
    document.removeEventListener('visibilitychange', this.handleVisibilityChange)
  },
  methods: {
    async loadMe () {
      const { data } = await axios.get('/api/user/me')
      if (data.code === 1) {
        this.user = data.data
        this.editForm.avatarUrl = this.user.avatarUrl
        this.editForm.username = this.user.username
        this.editForm.nickname = this.user.nickname
        this.editForm.phone = this.user.phone
        this.editForm.bio = this.user.bio

        // 实时更新用户统计数据
        await this.updateUserStats()
      }
    },
    async updateUserStats () {
      try {
        // 获取用户发布数量
        const postsRes = await axios.get('/api/user/posts', { params: { page: 1, size: 1 } })
        if (postsRes.data.code === 1) {
          this.$set(this.user, 'postCount', postsRes.data.data.total)
        }

        // 获取用户获赞总数
        try {
          const likesRes = await axios.get(`/api/interact/user/${this.user.id}/liked-count`)
          if (likesRes.data.code === 1) {
            this.$set(this.user, 'likedCount', likesRes.data.data.totalLikedCount)
          }
        } catch (e) {
          console.error('获取用户获赞总数失败:', e)
          // 如果接口失败，使用默认值
          this.$set(this.user, 'likedCount', 0)
        }
      } catch (error) {
        console.error('更新用户统计失败:', error)
      }
    },
    async loadPosts () {
      const params = { page: this.postPage, size: this.pageSize }
      // 使用新的接口获取包含实时统计信息的用户帖子列表
      const { data } = await axios.get(`/api/post/user/${this.user.id}`, { params })
      if (data.code === 1) {
        this.postList = data.data.records; this.postTotal = data.data.total
        for (const p of this.postList) {
          const d = await axios.get('/api/post/' + p.id)
          if (d.data.code === 1 && d.data.data.images && d.data.data.images.length) this.$set(this.thumb, p.id, d.data.data.images[0].url)
        }
        // 加载完成后更新用户统计
        await this.updateUserStats()
      }
    },
    toggleDeleteMode () { this.deleteMode = !this.deleteMode; if (!this.deleteMode) this.selectedIds = [] },
    onToggleSelect (id) {
      const set = new Set(this.selectedIds)
      if (set.has(id)) set.delete(id); else set.add(id)
      this.selectedIds = Array.from(set)
    },
    clearSelection () { this.selectedIds = [] },
    async confirmBatchDelete () {
      if (this.selectedIds.length === 0) return
      try {
        await this.$confirm('是否确认删除所选分享？', '确认删除', { type: 'warning', confirmButtonText: '确认删除', cancelButtonText: '取消' })
      } catch (e) { return }
      const ids = this.selectedIds.slice()
      const { data } = await axios.post('/api/post/batch-delete', ids)
      if (data.code === 1) {
        this.$message.success('删除成功')
        // 刷新当前页（若当前页被删空，回退一页）
        if (ids.length >= this.postList.length && this.postPage > 1) this.postPage -= 1
        this.selectedIds = []
        this.deleteMode = false
        await this.loadPosts()
      } else {
        this.$message.error(data.msg || '删除失败')
      }
    },
    async loadLikes () {
      const params = { page: this.likePage, size: this.pageSize }
      const { data } = await axios.get('/api/user/likes', { params })
      if (data.code === 1) {
        this.likeList = data.data.records; this.likeTotal = data.data.total
        for (const p of this.likeList) {
          const d = await axios.get('/api/post/' + p.id)
          if (d.data.code === 1 && d.data.data.images && d.data.data.images.length) this.$set(this.thumb, p.id, d.data.data.images[0].url)
        }
      }
    },
    onTab (tab) {
      if (tab.name === 'posts') this.loadPosts()
      if (tab.name === 'likes') this.loadLikes()
    },
    openEdit () { this.editVisible = true },
    onAvatarUploaded (res) { if (res.code === 1) this.editForm.avatarUrl = res.data.url },
    async submitEdit () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return
        // 资料
        const base = { avatarUrl: this.editForm.avatarUrl, nickname: this.editForm.nickname, bio: this.editForm.bio }
        await axios.post('/api/user/profile', base)
        // 如输入了密码项，则提交密码修改
        if (this.editForm.oldPassword || this.editForm.newPassword || this.editForm.confirmPassword) {
          const pwd = { oldPassword: this.editForm.oldPassword, newPassword: this.editForm.newPassword }
          const ret = await axios.post('/api/user/password', pwd)
          if (ret.data.code !== 1) { this.$message.error(ret.data.msg || '修改密码失败'); return }
        }
        this.$message.success('保存成功')
        this.editVisible = false
        this.loadMe()
        // 重新加载数据以更新统计
        await this.updateUserStats()
      })
    },
    handleVisibilityChange () {
      // 当页面重新可见时，更新用户统计数据
      if (!document.hidden) {
        this.updateUserStats()
      }
    }
  }
}
</script>

<style scoped>
.profile-page{ max-width: 1080px; margin: 20px auto; }
.user-card{ margin-bottom: 16px; }
.user-header{ display:flex; align-items:center; }
.avatar{ box-shadow: 0 4px 12px rgba(0,0,0,.08); }
.meta{ margin-left: 16px; }
.name{ font-weight: 700; font-size: 18px; display:flex; align-items:center; gap:8px }
.ml8{ margin-left: 8px; }
.bio{ color:#666; margin-top:6px }
.actions{ margin-top:10px }
.content-card{ }
.pg-title{ font-weight:600; font-size:14px; line-height:18px; margin-bottom:4px }
.pg-meta{ color:#999; font-size:12px }
.avatar-row{ display:flex; align-items:center; }
.ml12{ margin-left:12px; }
</style>
